if(!window.xflib || !window.xflib.client) window.xflib = { client: {} }

xflib.client.ProjectUi = class ProjectUi {

    constructor(projectService, categoryService, productService){
        this.projectModal = new xflib.client.ProjectModal();
        this.projectService = projectService;
        this.categoryService = categoryService;
        this.productService = productService;
        this.oldProjectCode = '';

        this.productSelect = document.getElementById('product-select');
        this.categorySelect = document.getElementById('category-select');
        this.projectSelect = document.getElementById('project-select');

        document.getElementById('projectAddbtn').addEventListener('click', this.projectAddbtnHandler.bind(this));
        document.getElementById('projectImportBtn').addEventListener('click', this.projectImportBtnHandler.bind(this));
        document.getElementById('projectImportInput').addEventListener('change', this.projectImportInputHandler.bind(this));
        document.getElementById('projectExportBtn').addEventListener('click', this.projectExportBtnHandler.bind(this)); 
        // 按产品、分类筛选，刷新项目清单
        document.getElementById('projectsFilterByProductBtn').addEventListener('click', this.projectsFilterHandler.bind(this));
        document.getElementById('projectsFilterByCategoryBtn').addEventListener('click', this.projectsFilterHandler.bind(this));
        //document.getElementById('projectsFilterBtn').addEventListener('click', this.projectsFilterHandler.bind(this));
        document.getElementById('projectDeleteBatchBtn').addEventListener('click', () => {
            // 获取当前选择的分类和产品
            const selectedCategory = this.categorySelect.value;
            const selectedProduct = this.productSelect.value;
            const selectedCategoryName = this.categorySelect.options[this.categorySelect.selectedIndex].data||'全部';
            const selectedProductName = this.productSelect.options[this.productSelect.selectedIndex].data||'全部';

            // 确认删除操作
            if (!confirm(`确定要删除 [产品="${selectedProductName}", 分类="${selectedCategoryName}"] 所有项目吗？`)) {
                return;
            }

            // 调用 ProjectService 中的方法删除项目
            this.projectService.deleteByProductAndCategory(selectedProduct,selectedCategory).then(response => {
                if (response.success) {
                    // 刷新项目列表
                    this.projectsFilterHandler();
                    // 检查并清理未使用的分类和产品
                    this.checkAndCleanUnusedCategoriesAndProducts();
                } else {
                    console.error('删除项目失败:', response.error);
                }
            }).catch(error => {
                console.error('删除项目时发生错误:', error);
            });
        });

        document.getElementById('fixedProductAndCatoryByProjectBtn').addEventListener('click', async () => {
            try {
                const projects = await this.projectService.queryByProjectCode();
                const usedCategories = new Set(Object.values(projects).map(project => project.category));
                const usedProducts = new Set(Object.values(projects).map(project => project.productCode));

                const categoryService = this.categoryService;
                const productService = this.productService;

                const allCategories = await categoryService.queryByCategoryCodes();
                const allProducts = await productService.queryByProductCodes();

                const missingCategories = [...usedCategories].filter(category => !allCategories.hasOwnProperty(category));
                const missingProducts = [...usedProducts].filter(product => !allProducts.hasOwnProperty(product));

                for (const category of missingCategories) {
                    await categoryService.create(category, category);
                }

                for (const product of missingProducts) {
                    await productService.create(product, product);
                }
                // 刷新项目列表
                window.xflib.client.Application.refreshUi();
                alert('修复完成。');
            } catch (error) {
                console.error('修复缺失的分类和产品时发生错误:', error);
            }
        });
    }

    // 添加项目按钮事件方法，打开新增窗口
    async projectAddbtnHandler(){
        this.projectModal.openModal('add',
             (projectCode, projectName, projectUrl, projectCategory, projectSerial, permissions, productCode, tag) => 
                this.saveProject(projectCode, projectName, projectUrl, projectCategory, projectSerial, permissions, productCode, tag));
    }

    // 项目表格行编辑按钮事件方法，打开编辑窗口
    async editProjectHandler(projectCode){
        // // 获取项目数据
        this.projectService.queryByProjectCode(projectCode).then(projectData =>{
            this.oldProjectCode=projectCode;
            // 打开编辑弹窗
            this.projectModal.openModal('edit', 
                (projectCode, projectName, projectUrl, projectCategory, projectSerial, permissions, productCode, tag) => 
                    this.saveProject(projectCode, projectName, projectUrl, projectCategory, projectSerial, permissions, productCode, tag), 
                projectCode, projectData.name, projectData.url, projectData.category, projectData.serial, projectData.permissions, 
                projectData.productCode); 
        });
    }

    // 项目表格行删除按钮事件方法，删除项目， 刷新项目清单
    async deleteProjectHandler(projectCode, projectName){
        // 删除项目
        const _this = this;
        
        if (!confirm(`确定要删除产品 "${projectName}" 吗？`)) {
            return;
        }
        
        // 从存储中删除项目
        _this.projectService.delete(projectCode).then(response => {
            if(response.success){
                // 刷新项目清单
                this.projectsFilterHandler();
            }
        });
    }

    // 编辑或新增保存项目，刷新项目清单
    async saveProject(projectCode, projectName, projectUrl, projectCategory, projectSerial, permissions, productCode, tag){
        const _this = this;
        let _project = await _this.projectService.queryByProjectCode(projectCode);
        return new Promise((resolve, reject) => {
            if (_project && (
                _project.name === projectName && 
                _project.url === projectUrl && 
                _project.category === projectCategory && 
                _project.serial === projectSerial && 
                _project.permissions === permissions && 
                _project.productCode === productCode
            )) {
                alert('项目信息没有被修改，无需保存!');
                reject(false);
            }

            try {
                if(tag === 'add'){
                    _this.projectService.create(projectCode, projectName, projectUrl, projectCategory, projectSerial, permissions, productCode).then(response => {
                        if(response.success){
                            //_this.refreshProjectSelect();
                            _this.refreshProjectTable();
                        }
                    });
                } else if(tag === 'edit'){
                    _this.projectService.update(this.oldProjectCode, projectCode, projectName, projectUrl, projectCategory, projectSerial, permissions, productCode).then(response => {
                        if(response.success){
                            //_this.refreshProjectSelect();
                            _this.refreshProjectTable();
                        }
                    });
                }

                resolve(true);
            } catch(e) {
                reject(false);
            }
        });
    }

    // 按产品、分类筛选，刷新项目清单
    async projectsFilterHandler(){
        const productCode = this.productSelect.value||'all';
        const category = this.categorySelect.value||'all';

        if(category === 'all' && productCode === 'all'){
            this.refreshProjectTable();
        }else if(productCode === 'all'){
            this.projectService.queryByCategory(category).then(response => {
                this.refreshProjectTableView(response);
            });
        }else if(category === 'all'){
            this.projectService.queryByProductCode(productCode).then(response => {
                this.refreshProjectTableView(response);
            });
        }else{
            this.projectService.queryByProductCodeAndCategory(productCode, category).then(response => {
                this.refreshProjectTableView(response);
            });
        }
    }

    // 无条件刷新项目清单
    refreshProjectTable() {
        // 获取项目数据
        this.projectService.queryByProjectCode().then(projects => {
            this.refreshProjectTableView(projects);
        }).catch(error => {
            console.error('获取项目数据失败:', error);
        });
    }

    // 刷新项目清单(按projects渲染ui)
    refreshProjectTableView(projects){
        const projectTableBody = document.getElementById('project-table-body');
        projectTableBody.innerHTML = '';

        const projectEntries = Object.entries(projects);
        projectEntries.sort((a, b) => a[1].serial - b[1].serial); // 按 serial 排序

        projectEntries.forEach(([code, project], index) => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td hidden>${code}</td>
                <td>${project.serial}</td>
                <td>${project.productCode}</td>
                <td>${project.name}</td>
                <td>${project.category}</td>
                <td><a href="${project.url}" target="_${code}" class="project-link">${project.url}</a></td>
                <td>${this.getPermissionUrl(code, project)}</td>
                <td style="width: 10%; align-self: self-end; text-align: right;">
                    <button class="icon-button edit-button" title="编辑">
                        <i class="fas fa-edit"></i>
                    </button>
                    <button class="icon-button delete-button" data="${project.name}" title="删除">
                        <i class="fas fa-trash"></i>
                    </button>
                    <button class="icon-button move-row-button" draggable="true" title="改变编译顺序">
                        <i class="fas fa-arrows-alt-v"></i>
                    </button>
                </td>
            `;
            projectTableBody.appendChild(row);

            // 为行编辑/删除按钮添加事件监听
            row.querySelector('.edit-button').addEventListener('click', () => { this.editProjectHandler(code); });
            row.querySelector('.delete-button').addEventListener('click', () => { this.deleteProjectHandler(code, project.name); });
            let moveRowButton = row.querySelector('.move-row-button');
            
            // 添加拖放事件监听
            moveRowButton.addEventListener('dragstart', (e) => {
                e.dataTransfer.setData('text/plain', index);
                row.classList.add('highlight');
                row.classList.add('dragging');
            });

            moveRowButton.addEventListener('dragover', (e) => {
                e.preventDefault();
                const draggingRow = document.querySelector('.dragging');
                if (draggingRow && draggingRow !== row) {
                    const bounding = row.getBoundingClientRect();
                    const offset = bounding.y + bounding.height / 2;
                    if (e.clientY - offset > 0) {
                        projectTableBody.insertBefore(draggingRow, row.nextSibling);
                    } else {
                        projectTableBody.insertBefore(draggingRow, row);
                    }
                }
            });

            moveRowButton.addEventListener('dragend', () => {
                row.classList.remove('dragging');
                row.classList.remove('highlight');
                this.updateSerialsAndRefresh(Array.from(projectTableBody.children).map(tr => {
                    const code = tr.children[0].textContent;
                    return [code, projects[code]];
                }));

            });
        });
    }

    updateSerialsAndRefresh(projectEntries) {
        projectEntries.forEach(([code, project], index) => {
            project.serial = index + 1;
        });
        this.projectService.updateBatch(Object.fromEntries(projectEntries));
        this.refreshProjectTableView(Object.fromEntries(projectEntries));
    }

    PERMISSION_LABEL_MAP = {
        'edit': '项目',
        'branches': '分支',
        'tags': '标签',
        'members': '成员',
        'repository': '仓库',
        'commits': '提交'
    };
    
    PERMISSION_URL_MAP = {
        edit:'/edit',
        branches:'/-/branches',
        tags:'/-/tags',
        members:'/-/project_members',
        repository:'/-/settings/repository',
        commits:'/-/commits'
    };

    getPermissionUrl(code, project){
        let permissions = project.permissions;
        if(typeof permissions === 'string'){
            permissions = project.permissions.split(',');
        }
        if(Array.isArray(permissions)){
            return permissions.map(permission => 
                `<a href="${project.url}${this.PERMISSION_URL_MAP[permission]}" class="permission-link" target="_${code}">${this.PERMISSION_LABEL_MAP[permission]}</a>`).join(',');
        }
    
        return permissions;
    }


    //导入项目button事件方法
    projectImportBtnHandler(){
        document.getElementById('projectImportInput').click();
    }

    //导入项目input事件方法
    projectImportInputHandler(event){
        const file = event.target.files[0]; // 获取上传的文件
        if (!file) {
            alert('请上传一个文件');
            return;
        }
        this.projectService.importProjects(file);
    }


    //导出所有项目
    projectExportBtnHandler(){
        const productCode = this.productSelect.value||'all';
        const category = this.categorySelect.value||'all';

        this.projectService.exportProjects(productCode, category);
    }

    // 检查并清理未使用的分类和产品
    async checkAndCleanUnusedCategoriesAndProducts(){
        const result = await this.projectService.checkAndCleanUnusedCategoriesAndProducts();
        if(result.result){
            if (confirm('检测到未被引用的分类和产品，是否进行清理？')) {
                for (const category of result.unusedCategories) {
                    await this.categoryService.delete(category.code);
                }
                for (const product of result.unusedProducts) {
                    await this.productService.delete(product.code);
                }
                window.xflib.client.Application.refreshUi();
                alert('清理完成。');
            }
        }
    }


} 